const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const logger = require("morgan");
const Data = require("./data");

const API_PORT = 3001;
 
const app = express();

const router = express.Router();

//定义mongo数据库

const dbRoute = "mongodb://127.0.0.1:27017/notebook_app";

//连接数据库

mongoose.connect(
	dbRoute,
	{ useNewUrlParser: true }
);

let db = mongoose.connection;

db.once("open",()=>console.log("connected to the database"));

//检测数据库是否连接成功
db.on("error",console.error.bind(console, "MongoDB connection error"));

// 转换为可读的json
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

//开启日志
app.use(logger("dev"));

app.all("*",function(req,res,next){
	//设置允许跨域的域名，*代表允许任意域名跨域
	res.header("Access-Control-Allow-Origin","*");
    //设置允许跨域的域名，*代表允许任意域名跨域
    // res.header("Access-Control-Allow-Origin","http://localhost:3000");
    //允许的header类型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
}
)

router.get("/getD", (req, res) => {
	return {
		success: true,
		data: []
	}
})

//获取数据库中的方法

router.get("/getData", (req, res) => {
	Data.find((err, data) => {
		if(err) return res.json({success: false, error: err});
		console.log(data);
		return res.json({success: true, data: res});
	});
});



//数据更新方法

router.post("/updateData",(req, res)=>{
	const { id, update } = req.body;
	Data.findOneAndUpdate(id, update, err=>{
		if(err) return res.json({success: false, error: err});
		return res.json({success: true, data: res});
	})
})

//数据删除方法

router.delete("/deleteData", (req, res) => {
	const { id } = req.body;
	Data.findOneAndDelete(id, err=>{
		if(err) return res.send(err);
		return res.json({success: true});
	});
});

//添加数据方法
router.post("/putData", (req, res)=> {
	let data = new Data();
	
	const { id, message  } = req.body;
	if(!id && id!==0 || !message){
		return res.json({
			success: false,
			error: "INVALID INPUTS"
		});
	}
	data.message = message;
	data.id = id;
	data.save(err => {
		if(err) return res.send(err);
		return res.json({success: true});
	});
});

//对http请求添加/api路由

app.use("/api",router);

//开启端口
app.listen(API_PORT, ()=> console.log(`LISTENING ON PORT${API_PORT}`));